package com.adong.springboot.controller;

import com.adong.springboot.dao.DepartmentDao;
import com.adong.springboot.dao.EmployeeDao;
import com.adong.springboot.entities.Department;
import com.adong.springboot.entities.Employee;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    DepartmentDao departmentDao;

    /**
     * 查询全部数据集合
     *
     * @param model
     * @return
     */
    @GetMapping("/emps")
    public String list(Model model) {
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps", employees);
        return "emp/list";
    }

    /**
     * 来到员工添加页面,并查询部门信息
     *
     * @param model
     * @return
     */
    @GetMapping("/emp")
    public String toPage(Model model) {
        //查询出全部的部门信息
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts", departments);
        return "emp/add";
    }

    /**
     * 员工添加
     * SpringMVC自动将请求参数和入参对象的属性一一绑定,要去了请求参数的名字
     *
     * @return
     */
    @PostMapping("/emp")
    public String addEmp(Employee employee) {
        //保存员工
        employeeDao.save(employee);
        /*
        如果不使用重定向或者转发,thymeleaf会当成网页名去templates里面找
        返回员工列表页面
        redirect : 表示重定向到一个地址
        forward : 表示转发到一个地址
        /:代表当前项目的路径 http:localhost:8080/springboot
         */
        return "redirect:/emps";
    }

    //来到修改页面,查出当前员工,页面页面回显
    @GetMapping("/emp/{id}")
    public String editPage(@PathVariable("id") Integer id, Model model) {
        //根据id查询员工
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp", employee);
        //查询部门信息
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts", departments);
        //回到修改页面
        return "emp/add";
    }

    //员工修改更新
    @PutMapping("/emp")
    public String update(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    /**
     * 删除员工
     *
     * @param id
     * @return
     */
    @DeleteMapping("/emp/{id}")
    public String delete(@PathVariable("id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
